/**
 * 
 * Copyright (C) 2011 Cody Stoutenburg . All rights reserved.
 *
 *       This program is free software; you can redistribute it and/or
 *       modify it under the terms of the GNU Lesser General Public License
 *       as published by the Free Software Foundation; either version 2.1
 *       of the License, or (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *       but WITHOUT ANY WARRANTY; without even the implied warranty of
 *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *       GNU Lesser General Public License for more details.
 *
 *       You should have received a copy of the GNU Lesser General Public License
 *       along with this program; if not, write to the Free Software
 *       Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 * 
 */
package ca.usherbrooke.behaviours;

import jade.core.Agent;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

/**
 * @author Cody Stoutenburg
 * 
 */
public abstract class BasicRequestBehaviour<E extends Agent> extends
		BasicBehaviour<E> {
	private static final long serialVersionUID = 1L;

	public static final String MY_REQUEST = "proto.request";

	private final static MessageTemplate RESULT_TEMPLATE = MessageTemplate.and(
			MessageTemplate.MatchProtocol(BasicRequestBehaviour.MY_REQUEST),
			MessageTemplate.MatchPerformative(ACLMessage.INFORM));

	private final MessageTemplate template;
	private Boolean isMessageReceive;

	/**
	 * @param a
	 */
	public BasicRequestBehaviour(E a, ACLMessage msg) {
		this(a, msg, RESULT_TEMPLATE);
	}

	public BasicRequestBehaviour(E a, ACLMessage msg, MessageTemplate template) {
		super(a);
		isMessageReceive = false;

		this.template = template;

		if (msg.getProtocol() == null) {
			msg.setProtocol(MY_REQUEST);
		}
		msg.setPerformative(ACLMessage.REQUEST);
		this.getAgent().send(msg);
	}

	protected void sendMessage(ACLMessage msg) {

	}

	@Override
	public void action() {
		ACLMessage msg = this.getAgent().receive(template);
		if (msg != null) {
			isMessageReceive = true;
			messageReceive(msg);
		} else {
			block();
		}
	}

	@Override
	public boolean done() {
		return isMessageReceive;
	}

	public abstract void messageReceive(ACLMessage resut);

}
